let WIDTH, HEIGHT;
(function () {
    let root = document.getElementById('root');
    WIDTH  = root.width  = window.innerWidth;
    HEIGHT = root.height = window.innerHeight;
}) ();

$(function () {
    $.ajax ({url:'backend/server-info'}).done (function (response) {
        console.log (response);

        DrawingLib.init ({canvas:'#root'});
        socket.connect (response ['context-path'] + '/ws/monitor');
    });

    const MAPPINGS = {
        '[Z':'boolean[]',
        '[B':'byte[]',
        '[S':'short[]',
        '[C':'char[]',
        '[I':'int[]',
        '[J':'long[]',
        '[F':'float[]',
        '[D':'double[]'
    };

    function patchTypeName (name) {
        if (name[0] !== '[') {
            return name;
        }

        if (name[1] === 'L') {
            return name.substring (2, name.length - 1) + '[]';
        }

        if (name[1] in MAPPINGS) {
            return MAPPINGS [name[1]];
        }
        throw "Unknown Type!";
    }

    function onCreate (message) {
        if (!('data' in message) || !('frames' in message.data)) {
            console.warn ('empty data: ', message);
            return;
        }

        let frames = message.data.frames, k;
        for (k in frames) if (frames.hasOwnProperty (k)) {
            let srf = build (patchItems (frames[k]));
            DrawingLib.add (new SRFNode (srf, 100, 100));
        }
        DrawingLib.render ();
        // console.log ('table = ', table);
    }

    function build (raw) {
        let items = [];
        if ('items' in raw) {
            for (let k in raw.items) if (raw.items.hasOwnProperty (k)) {
                let item = raw.items [k];
                let sri = new ServiceRouteItem ({
                    endpoint: item.name,
                    type: item.types,
                    methods: item.methods
                });
                items.push (sri);
            }
        }
        return new ServiceRouteFrame ({
            namespace: raw.namespace, host: raw.host,
            port: raw.port, metric: raw.metric,
            timestamp: raw.timestamp, items: items
        });
    }

    function patchItems (srf) {
        srf.id = Math.random().toString ().substring (2);

        if ('items' in srf) {
            let item, i, j, k, method, parameter;
            for (k in srf.items) if (srf.items.hasOwnProperty (k)) {
                item = srf.items [k];

                if (('types' in item) && item.types.length) {
                    for (i = 0; i < item.types.length; i ++) {
                        item.types [i] = patchTypeName (item.types [i]);
                    }
                }

                if (('methods' in item) && item.methods.length) {
                    for (i = 0; i < item.methods.length; i ++) {
                        method = item.methods[i];
                        method.type = patchTypeName (method.type);

                        if (('parameters' in method) && method.parameters.length) {
                            for (j = 0; j < method.parameters.length; j ++) {
                                parameter = method.parameters[j];
                                parameter.type = patchTypeName (parameter.type);
                            }
                        }
                    }
                }
            }
        }

        return srf;
    }

    let socket = new WebSocketWrapper ({
        onopen : function () {
            console.log ('web socket opened');
        },
        onclose : function () {
            console.log ('web socket closed');
        },
        onmessage : function (message) {
            message = JSON.parse (message);
            console.log ('received a message: ', message);

            switch (message.action) {
                case 'create':
                    onCreate (message);
                    break;
                case 'update':
                    break;
                case 'withdrawn':
                    break;
                default :
                    console.warn ('unknown command');
            }
        }
    });

/*
    $('#btn-open').on ('click', function () {
        socket.connect ('ws://localhost:9090/monitor/ws/monitor');
    });
    $('#btn-close').on ('click', function () {
        socket.disconnect ();
    })
    $('#btn-send').on ('click', function () {
        socket.send ($('#txt-content').val ());
    })
*/
});